<template>
  <div>
    <el-form ref="depFormRef" :model="depForm" :rules="depFormRules">
      <el-form-item label="部门名称" prop="name" label-width="100px">
        <el-input v-model="depForm.name" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code" label-width="100px">
        <el-input v-model="depForm.code" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager" label-width="100px">
        <el-select v-model="depForm.manager" placeholder="请选择" style="width: 100%">
          <el-option
            v-for="item in employees"
            :key="item.id"
            :value="item.username"
            :label="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce" label-width="100px">
        <el-input v-model="depForm.introduce" type="textarea" placeholder="1-300个字符" :rows="3" />
      </el-form-item>
      <el-form-item style="text-align: center">
        <el-button type="primary" @click="submitDep">确定</el-button>
        <el-button @click="$emit('success')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeeSimple, addDepartments, getDepartDetail, editDepartment } from '@/api/departments'
import { Message } from 'element-ui'
export default {
  props: {
    pid: {
      required: true,
      type: String
    },
    isEdit: {
      required: true,
      type: Boolean
    },
    originList: {
      required: true,
      type: Array
    },
    ppid: {
      required: true,
      type: String
    }
  },
  data() {
    // 自定义code校验规则
    const validCode = (rule, value, callback) => {
      // 获取每个元素的code组成数组
      let codeList = this.originList.map(item => item.code)
      // 如果是编辑就排除自身的code
      if (this.isEdit) {
        codeList = this.originList.filter(item => item.id !== this.pid).map(item => item.code)
      }
      if (codeList.includes(value)) {
        callback(new Error(`${value}已经被占用`))
      } else {
        callback()
      }
    }
    // 自定义name校验规则
    const validName = (rule, value, callback) => {
      let nameList = []
      // 如果是编辑部门就获取与被点击的部门有相同pid的部门的name组成数组
      if (this.isEdit) {
        nameList = this.originList.filter(item => item.pid === this.ppid).filter(item => item.id !== this.pid).map(item => item.name)
        console.log(nameList)
      } else { // // 如果是新增部门就获取被点击的父部门的子部门的name组成数组
        nameList = this.originList.filter(item => item.pid === this.pid).map(item => item.name)
      }
      if (nameList.includes(value)) {
        callback(new Error(`${value}已经被占用`))
      } else {
        callback()
      }
    }
    return {
      // 对话框表单数据
      depForm: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      // 对话框表单校验规则
      depFormRules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称长度为1-50个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }

        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称长度为1-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: ['blur', 'change'] }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门名称长度为1-300个字符', trigger: 'blur' }
        ]
      },
      // 员工基本列表
      employees: []
    }
  },
  created() {
    this.loadEmployee()
    // 如果是编辑部门就加载部门信息
    if (this.isEdit) {
      this.loadDepDetail()
    }
  },
  // methods:事件处理函数
  methods: {
    // 加载员工列表
    async loadEmployee() {
      const res = await getEmployeeSimple()
      this.employees = res.data.data
    },
    // 添加或编辑部门
    submitDep() {
      // 兜底校验
      this.$refs.depFormRef.validate(async valid => {
        if (valid) {
          // 编辑部门
          if (this.isEdit) {
            await editDepartment(this.depForm)
            // 子传父告诉父组件关闭弹窗刷新列表
            this.$emit('success')
          } else { // 新增部门
            await addDepartments({ ...this.depForm, pid: this.pid })
            // 子传父告诉父组件关闭弹窗刷新列表
            this.$emit('success')
            // 清空对话框表单数据
            this.depForm = {
              name: '',
              code: '',
              manager: '',
              introduce: ''
            }
          }
        } else {
          Message.error('表单校验不通过')
        }
      })
    },
    // 编辑部门
    async loadDepDetail() {
      const res = await getDepartDetail(this.pid)
      // 将返回的数据绑定到data中的depForm中
      this.depForm = res.data.data
    }
  }
}
</script>

<style>

</style>
